<?php

namespace oa\controllers;

use Yii;
use Smalot\PdfParser\Parser;
use oa\modules\Auth\services\AuthMenuService;
use yii\db\Query;
use yii\web\UploadedFile;

/**
 * Site controller
 */
class SiteController extends BaseController
{

    public function actionIndex()
    {
        return $this->fetch();
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();
        return $this->goHome();
    }

    public function actionMy()
    {
        return $this->fetch();
    }

    public function actionUpload()
    {
        $file = UploadedFile::getInstanceByName('file');
        if (!$file) {
            return $this->err('请选择要上传的文件');
        }
        if ($file->error != 0) {
            return $this->err('上传资源不正确');
        }
        $file_key = $this->request->post('file_key');
        if (!$file_key) {
            return $this->err('上传参数错误');
        }
        $config = Yii::$app->params['upload'];
        if (!isset($config['files'][$file_key])) {
            return $this->err('未知文件上传');
        }
        $fileConfig = $config['files'][$file_key];
        $minSize = isset($fileConfig['min_size']) ? $fileConfig['min_size'] : $config['min_size'];
        if ($file->size < $minSize) {
            $minSizeInfo = $minSize < 1024 * 1024 ? ceil($minSize/1024) . 'K' : ceil($minSize/1024) . 'M';
            return $this->err('上传文件不能小于' . $minSizeInfo);
        }

        $maxSize = isset($fileConfig['max_size']) ? $fileConfig['max_size'] : $config['max_size'];
        if ($file->size > $maxSize) {
            $maxSizeInfo = $maxSize < 1024 * 1024 ? floor($maxSize/1024) . 'K' : floor($maxSize/1024) . 'M';
            return $this->err('上传文件不能小于' . $maxSizeInfo);
        }

        if ($fileConfig['type'] == 1) {
            $allowExts = isset($fileConfig['exts']) ? $fileConfig['exts'] : $config['img_exts'];
            $fileConfig['path'] = isset($fileConfig['path']) ? $fileConfig['path'] : $config['img_path'];
        } elseif ($fileConfig['type'] == 2) {
            $allowExts = isset($fileConfig['exts']) ? $fileConfig['exts'] : $config['file_exts'];
            $fileConfig['path'] = isset($fileConfig['path']) ? $fileConfig['path'] : $config['file_path'];
        } elseif ($fileConfig['type'] == 3) {
            $allowExts = isset($fileConfig['exts']) ? $fileConfig['exts'] : $config['video_exts'];
            $fileConfig['path'] = isset($fileConfig['path']) ? $fileConfig['path'] : $config['video_path'];
        } else {
            $allowExts = isset($fileConfig['exts']) ? $fileConfig['exts'] : array_merge($config['img_exts'], $config['file_exts']) ;
            $fileConfig['path'] = isset($fileConfig['path']) ? $fileConfig['path'] : $config['file_path'];
        }
        if (!is_array($allowExts)) {
            $allowExts = explode(",", $allowExts);
        }
        $fileExt = $file->getExtension();
        if (!in_array($fileExt, $allowExts)) {
            return $this->err('上传文件类型必须是' . implode("，", $allowExts));
        }

        $fileName = md5(rand(1, 9999).time()).'.'.$fileExt;
        $date = date('Ymd');
        $y = substr($date, 0, 4);
        $m = substr($date, 4, 2);
        $d = substr($date, 6, 2);
        $filePath =  $fileConfig['path'].'/'.$y.$m.'/'.$d.'/';
        $saveDir = $config['tmp_path'] . $filePath;
        is_dir($saveDir) or mkdir($saveDir, 0777, true);
        $save = $file->saveAs($saveDir.$fileName);
        if ($save) {
            return $this->ok('上传成功', [
                'filename' => $file->name,
                'filepath' => $saveDir . $fileName,
            ]);
        }
        return $this->err('上传失败，请重试');
    }

    public function actionSeekPassword()
    {
        if (Yii::$app->request->isPost) {
            $res = AdminService::editPassword();
            if ($res === true) {
                $this->msg_ok = '修改成功';
                $this->ok();
            }
            $this->fail(reset($res));
        }
        return $this->fetch();
    }

    public function error()
    {
        echo 1;
        exit;
    }

    public function actionReloadmenu()
    {
        if (AuthMenuService::set(1) !== false) {
            return $this->ok('刷新成功');
        }
        return $this->err('刷新失败，请重试');
    }

    public function actionRegions()
    {
        $query = (new Query())->select('short_name')->from('region');
        $pid = $this->input('pid', 0);
        $result = [];
        if ($pid == 0) {
            $rows = $query->where('level=1 and status=1')->indexBy('id')->column();
            foreach ($rows as $k => $v) {
                $result[substr($k, 0, 2)] = $v;
            }
            return $result;
        } else {
            if (strlen($pid) == 2) {
                $pid2 = $pid * 10000;
            } elseif (strlen($pid) == 4) {
                $pid2 = $pid * 100;
            }
            
            $rows = $query->where('pid=:pid and status=1', [':pid' => $pid2])->indexBy('id')->column();
            if (strlen($pid) == 2) {
                foreach ($rows as $k => $v) {
                    $result[substr($k, 0, 4)] = $v;
                }
            } else {
                return $rows;
            }

            return $result;
        }
    }



}
